package org.joinme.backend.controller;

import org.joinme.backend.model.CarPoolingRecord;
import org.joinme.backend.model.ParticipateRecord;
import org.joinme.backend.service.ParticipateService;
import org.joinme.backend.service.CarPoolingService;
import org.joinme.backend.service.WechatUserService;
import org.joinme.backend.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping(value = {"/{appName}/wechat/carpooling"}, produces = {"application/json;charset=UTF-8"})
public class CarPoolingController {
    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private WechatUserService userService;

    @Autowired
    private CarPoolingService carPoolingService;

    @Autowired
    private ParticipateService participateService;

    //添加拼单记录
    @ResponseBody
    @RequestMapping("/record/add")
    public String addCarPoolingRecord(HttpServletRequest request, CarPoolingRecord carPoolingRecord){
        try {
            //拼单的出发地，终点以及出发时间不能为空
            if(StringUtil.isEmpty(carPoolingRecord.getStartLocation()))
                throw new PrjException(ErrorCodeMsg.CAR_POOLING_RECORD_START_LOCATION_EMPTY);

            if(StringUtil.isEmpty(carPoolingRecord.getEndLocation()))
                throw new PrjException(ErrorCodeMsg.CAR_POOLING_RECORD_END_LOCATION_EMPTY);

            if(StringUtil.isEmpty(carPoolingRecord.getDepartTime()))
                throw new PrjException(ErrorCodeMsg.CAR_POOLING_RECORD_DEPART_TIME_EMPTY);

            //获取登陆的用户信息
            int userId = userService.getLoginUserId(request);

            //发布拼单成功
            int result = carPoolingService.addCarPoolingRecord(carPoolingRecord);
            if(result > 0) {
                //以发布者身份添加participate记录
                ParticipateRecord participateRecord = new ParticipateRecord();
                participateRecord.setUserId(userId);
                log.debug(String.format("The inserted carpooling id is %d", carPoolingRecord.getCarPoolingId()));
                participateRecord.setCarPoolingId(carPoolingRecord.getCarPoolingId());
                participateRecord.setParticipateRole(ConstUtil.ROLE_PUBLISHER);
                participateRecord.setParticipateTime(DateUtil.getCurrentTime());
                participateRecord.setParticipateStatus(ConstUtil.PARTICIPATE_ING);

                if(participateService.addParticipateRecord(participateRecord)){
                    return ApiResult.SUCCESS;
                }else{
                    throw new PrjException(ErrorCodeMsg.PARTICIPATE_RECORD_ADD_ERROR);
                }
            } else
                throw new PrjException(ErrorCodeMsg.CAR_POOLING_RECORD_ADD_ERROR);
        } catch (PrjException e){
            log.error(ApiJson.toJson(request.getParameterMap()));
            log.error("Error message : " + e.getErrMsg());
            return ApiResult.writeException(e);
        } catch (Exception e) {
            log.error(ApiJson.toJson(request.getParameterMap()));
            log.error(PrjException.getTrace(e));
            return ApiResult.SYSTEM_ERROR;
        }
    }

    //查询拼单列表
    @ResponseBody
    @RequestMapping("/record/list")
    public String listCarPoolingRecord(HttpServletRequest request,
                                  @RequestParam(required = false, defaultValue = "0") int start,
                                  @RequestParam(required = false, defaultValue = "10") int limit){
        try {
            int userId = userService.getLoginUserId(request);

            if(start == 0)
                return ApiResult.writeData(carPoolingService.getCarPoolingList(userId, start, limit), carPoolingService.countCarPoolingList(userId));
            else
                return ApiResult.writeData(carPoolingService.getCarPoolingList(userId, start, limit));
        } catch (PrjException e){
            return ApiResult.writeException(e);
        } catch (Exception e) {
            log.error(ApiJson.toJson(request.getParameterMap()));
            log.error(PrjException.getTrace(e));
            return ApiResult.SYSTEM_ERROR;
        }
    }

    //查询我的正在进行的拼单
    @ResponseBody
    @RequestMapping("/record/list_ing")
    public String listCarPoolingRecordIng(HttpServletRequest request,
                                  @RequestParam(required = false, defaultValue = "0") int start,
                                  @RequestParam(required = false, defaultValue = "10") int limit){
        try {
            int userId = userService.getLoginUserId(request);

            if(start == 0)
                return ApiResult.writeData(carPoolingService.getCarPoolingListIng(userId, start, limit), carPoolingService.countCarPoolingListIng(userId));
            else
                return ApiResult.writeData(carPoolingService.getCarPoolingListIng(userId, start, limit));
        } catch (PrjException e){
            return ApiResult.writeException(e);
        } catch (Exception e) {
            log.error(ApiJson.toJson(request.getParameterMap()));
            log.error(PrjException.getTrace(e));
            return ApiResult.SYSTEM_ERROR;
        }
    }

    //查询我的历史拼单
    @ResponseBody
    @RequestMapping("/record/list_ed")
    public String listCarPoolingRecordEd(HttpServletRequest request,
                                          @RequestParam(required = false, defaultValue = "0") int start,
                                          @RequestParam(required = false, defaultValue = "10") int limit){
        try {
            int userId = userService.getLoginUserId(request);

            if(start == 0)
                return ApiResult.writeData(carPoolingService.getCarPoolingListEd(userId, start, limit), carPoolingService.countCarPoolingListEd(userId));
            else
                return ApiResult.writeData(carPoolingService.getCarPoolingListEd(userId, start, limit));
        } catch (PrjException e){
            return ApiResult.writeException(e);
        } catch (Exception e) {
            log.error(ApiJson.toJson(request.getParameterMap()));
            log.error(PrjException.getTrace(e));
            return ApiResult.SYSTEM_ERROR;
        }
    }

    //查询拼单详情
    @ResponseBody
    @RequestMapping("/record/detail")
    public String getCarPoolingRecordDetail(HttpServletRequest request, @RequestParam int carPoolingId){
        try {
            int userId = userService.getLoginUserId(request);
            return ApiResult.writeData(carPoolingService.getCarPoolingRecordDetail(userId, carPoolingId));
        } catch (PrjException e){
            return ApiResult.writeException(e);
        } catch (Exception e) {
            log.error(ApiJson.toJson(request.getParameterMap()));
            log.error(PrjException.getTrace(e));
            return ApiResult.SYSTEM_ERROR;
        }
    }

    //查询拼单详情
    @ResponseBody
    @RequestMapping("/record/complete")
    public String completeCarPoolingRecord(HttpServletRequest request, @RequestParam int carPoolingId){
        try {
            int userId = userService.getLoginUserId(request);
            return ApiResult.writeData(carPoolingService.completeCarPoolingRecord(userId, carPoolingId));
        } catch (PrjException e){
            return ApiResult.writeException(e);
        } catch (Exception e) {
            log.error(ApiJson.toJson(request.getParameterMap()));
            log.error(PrjException.getTrace(e));
            return ApiResult.SYSTEM_ERROR;
        }
    }

    //查询聊天消息
    @ResponseBody
    @RequestMapping("/message/get")
    public String getCarPoolingRecordMessage(HttpServletRequest request, @RequestParam int carPoolingId){
        try {
            int userId = userService.getLoginUserId(request);
            return ApiResult.writeData(carPoolingService.getCarPoolingRecordMessage(userId, carPoolingId));
        } catch (PrjException e){
            return ApiResult.writeException(e);
        } catch (Exception e) {
            log.error(ApiJson.toJson(request.getParameterMap()));
            log.error(PrjException.getTrace(e));
            return ApiResult.SYSTEM_ERROR;
        }
    }

    //添加聊天消息
    @ResponseBody
    @RequestMapping("/message/add")
    public String addCarPoolingRecordMessage(HttpServletRequest request, @RequestParam int carPoolingId, @RequestParam String message){
        try {
            int userId = userService.getLoginUserId(request);
            return ApiResult.writeData(carPoolingService.addCarPoolingRecordMessage(userId, carPoolingId, message));
        } catch (PrjException e){
            return ApiResult.writeException(e);
        } catch (Exception e) {
            log.error(ApiJson.toJson(request.getParameterMap()));
            log.error(PrjException.getTrace(e));
            return ApiResult.SYSTEM_ERROR;
        }
    }
}
